/**
 * @author shaosong
 * @description
 */
import { Input } from '@nextui-org/react'
import React, { useEffect } from 'react'
import NextIcon from '../NextIcon'
import { reg } from 'regexp-utils-lib'

export class PassWordInputProps {
  defaultValue?: string
  value?: string
}

const PassWordInput: React.FC<PassWordInputProps> = props => {
  const [value, changeValue] = React.useState<string | undefined>(
    props?.defaultValue
  )

  const [isVisible, setIsVisible] = React.useState(false)

  const toggleVisibility = () => setIsVisible(!isVisible)

  const validateEmail = (value: string | undefined) => value?.match(reg.mail)

  const isInvalid = React.useMemo(() => {
    if (!value) return false

    return validateEmail(value) ? false : true
  }, [value])

  useEffect(() => {
    if (props?.value !== value) {
      changeValue(props?.value)
    }
  }, [props?.value])

  return React.useMemo(
    () => (
      <Input
        type={isVisible ? 'text' : 'password'}
        label="Password"
        placeholder="please input password"
        labelPlacement="outside"
        endContent={
          <button
            className="focus:outline-none"
            type="button"
            onClick={toggleVisibility}
            aria-label="toggle password visibility"
          >
            {isVisible ? (
              <NextIcon
                type="eye-close"
                size={16}
                className="text-default-400 pointer-events-none"
              />
            ) : (
              <NextIcon
                type="eye"
                size={16}
                className="text-default-400 pointer-events-none"
              />
            )}
          </button>
        }
        value={value}
        onValueChange={changeValue}
      />
    ),
    [value, isVisible]
  )
}

export default PassWordInput
